import 'package:flutter/material.dart';
import 'package:flutter_color_plugin/flutter_color_plugin.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';
import 'package:lpinyin/lpinyin.dart';
import 'package:yw_bapp/dao/common_dao.dart';
import 'package:yw_bapp/model/bank_list_model.dart';
import 'package:yw_bapp/widgets/loading_pop_widget.dart';
import 'package:yw_bapp/widgets/safe_area_bar_widget.dart';
import 'package:yw_bapp/widgets/show_toast.dart';

class SelectBankPage extends StatefulWidget {
  @override
  _SelectBankPageState createState() => _SelectBankPageState();
}

class _SelectBankPageState extends State<SelectBankPage> {
  List<String> letters = [];
  List<Data> bankList;
  ScrollController _scrollController = ScrollController();
  int _currentIndex = 0;
  var banks = new Map<String, bankObject>();
  List<Data> list = [];
  @override
  void initState() {
    super.initState();
    getBanksList();
  }

  getBanksList() async {
    await CommonDao.GetBankList().then((BanksListModel model) => {
          if (model.status == 200)
            {
              setState(() {
                bankList = model.data;
                var flag = false;
                var title;
                for (int i = 0; i < bankList?.length ?? 0; i++) {
                  title =
                      PinyinHelper.getFirstWordPinyin(bankList[i].bankName)[0]
                          .toUpperCase();
                  flag = letters.contains(title);
                  if (!flag) {
                    letters.add(title);
                  }
                }
                _handleList();
              }),
              // 排序
              letters.sort(),
              bankList.sort((a, b) => a.bankName.compareTo(b.bankName)),
            }
        });
  }

  _handleList() {
    setState(() {
      var title;
      for (var j = 0; j < letters?.length; j++) {
        //遍历字母
        title = letters[j]; //当前的字母
        for (int i = 0; i < bankList?.length ?? 0; i++) {
          list = [];
          var Zindex = PinyinHelper.getFirstWordPinyin(bankList[i].bankName)[0]
              .toUpperCase(); //当前银行的首字母
          //给每个字母分配下面的银行
          if (Zindex == letters[j]) {
            //分配到当前的字母下
            if (banks[title] != null ?? false) {
              //含有字母
              list = banks[title].items;
              list.add(bankList[i]); //在原有的银行列表中添加
              banks[title] = bankObject(title, list);
            } else {
              //第一次遍历，不含有
              list.add(bankList[i]); //直接添加
              banks[title] = bankObject(title, list);
            }
          }
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: XAppBar(
        statusBarColor: ColorUtil.color('#FFC49226'),
        bgColor: ColorUtil.color('#FFC49226'),
        title: "选择银行卡",
        fun: () {},
      ),
      body: Stack(
        children: <Widget>[
          banks == null || banks.length == 0
              ? Text("")
              : Padding(
                  padding: EdgeInsets.only(left: 20),
                  child: ListView.builder(
                      controller: _scrollController,
                      itemCount: banks.length,
                      itemBuilder: (BuildContext context, int index) {
                        return Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            PhoneCodeIndexName(letters[index].toUpperCase()),
                            ListView.builder(
                                itemCount: banks[letters[index].toUpperCase()]
                                    .items
                                    .length,
                                itemBuilder:
                                    (BuildContext context, int index2) {
                                  return AnimationConfiguration.staggeredList(
                                      position: index2,
                                      duration: Duration(milliseconds: 575),
                                      child: SlideAnimation(
                                        verticalOffset:46.0,
                                        child: FadeInAnimation(
                                          child: Container(
                                            height: 46,
                                            child: GestureDetector(
                                              child: Padding(
                                                padding: EdgeInsets.symmetric(
                                                    vertical: 10),
                                                child: Row(
                                                  children: <Widget>[
                                                    Text(
                                                        // "123",
                                                        "${banks[letters[index].toUpperCase()].items[index2].bankName}",
                                                        style: TextStyle(
                                                            fontSize: 16,
                                                            color: Color(
                                                                0xff434343))),
                                                  ],
                                                ),
                                              ),
                                              onTap: () {
                                                Navigator.of(context).pop(banks[
                                                        letters[index]
                                                            .toUpperCase()]
                                                    .items[index2]
                                                    .bankName);
                                              },
                                            ),
                                          ),
                                        ),
                                      ));
                                },
                                shrinkWrap: true,
                                physics:
                                    NeverScrollableScrollPhysics()) //禁用滑动事件),
                          ],
                        );
                      }),
                ),
          Align(
            alignment: new FractionalOffset(1.0, 0.5),
            child: SizedBox(
              width: 25,
              child: Padding(
                padding: EdgeInsets.only(top: 20),
                child: ListView.builder(
                  itemCount: letters.length,
                  itemBuilder: (BuildContext context, int index) {
                    return GestureDetector(
                      child: ClipRRect(
                          borderRadius: BorderRadius.circular(12.5),
                          child: Container(
                            width: 25,
                            height: 25,
                            color: _currentIndex == index
                                ? ColorUtil.color("#FFC49226")
                                : Colors.transparent,
                            child: Center(
                              child: Text(
                                letters[index],
                                textAlign: TextAlign.center,
                                style: TextStyle(
                                    color: _currentIndex == index
                                        ? Colors.white
                                        : Colors.black),
                              ),
                            ),
                          )),
                      onTap: () {
                        setState(() {
                          _currentIndex = index;
                        });
                        print(index);
                        var tryOffset = 1;
                        var height = index * 45.0; //这个原始的height是字母标题的高度
                        for (int i = 0; i < index; i++) {
                          var Zindex = letters[i]; //应该滚到的字母
                          height += banks[Zindex].items.length * 46.0;
                        }
                        print(height);
                        _scrollController.animateTo(height,
                            duration: Duration(milliseconds: 300),
                            curve: Curves.ease);
                        // _scrollController.position.moveTo(height);

                        // ShowToast.toast(context,
                        //     msg: letters[index], position: ToastPostion.center);
                      },
                    );
                  },
                ),
              ),
            ),
          )
        ],
      ),
    );
  }
}

// ignore: must_be_immutable
class PhoneCodeIndexName extends StatelessWidget {
  String indexName;
  PhoneCodeIndexName(this.indexName);

  Widget build(BuildContext context) {
    return Container(
      height: 45,
      child: Padding(
        child: Text(indexName,
            style: TextStyle(fontSize: 20, color: Color(0xff434343))),
        padding: EdgeInsets.symmetric(vertical: 10),
      ),
    );
  }
}

class bankObject {
  String title;
  List<Data> items = [];

  bankObject(this.title, this.items);
}

class bank {
  bankObject obj;
  bank(this.obj);
}
